/*
 * Copyright 2014 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package xin.alum.aim.websocks;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.AttributeKey;
import xin.alum.aim.Aim;
import xin.alum.aim.constant.AimAttr;
import xin.alum.aim.constant.AimClose;
import xin.alum.aim.handler.BaseServerHandler;

import java.net.URI;
import java.util.List;
import java.util.Map;

import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpResponseStatus.*;

/**
 * 处理握手和消息
 */
@ChannelHandler.Sharable
public class WebSocketServerHandler extends BaseServerHandler<Object> {

    private WebSocketServerHandshaker handshake;

    private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
        // Generate an error page if response getStatus code is not OK (200).
        HttpResponseStatus responseStatus = res.status();
        if (responseStatus.code() != 200) {
            ByteBufUtil.writeUtf8(res.content(), responseStatus.toString());
            HttpUtil.setContentLength(res, res.content().readableBytes());
        }
        // Send the response and close the connection if necessary.
        boolean keepAlive = HttpUtil.isKeepAlive(req) && responseStatus.code() == 200;
        HttpUtil.setKeepAlive(res, keepAlive);
        ChannelFuture future = ctx.writeAndFlush(res); // Flushed in channelReadComplete()
        if (!keepAlive) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof FullHttpRequest) {
            ctx.channel().eventLoop().execute(() -> {
                handleHttpRequest(ctx, (FullHttpRequest) msg);
            });
        } else if (msg instanceof WebSocketFrame) {
            handleWebSocketFrame(ctx, msg);
        } else {
            logger.error("{}上行未知消息类型", ctx.channel());
        }
    }

    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
        // Handle a bad request.
        if (!req.decoderResult().isSuccess()) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(req.protocolVersion(), BAD_REQUEST));
            return;
        }

        // Allow only GET methods.
        if (!GET.equals(req.method())) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(req.protocolVersion(), FORBIDDEN));
            return;
        }

        URI uri = URI.create(req.uri());
        FullHttpResponse res;
        if (uri.getPath().equals(Aim.properties.getPath())) {
            // Handshake
            WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, true);
            handshake = wsFactory.newHandshaker(req);
            if (handshake == null) {
                WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
            } else {
                //读取URL参数进行初始化
                QueryStringDecoder queryStringDecoder = new QueryStringDecoder(req.uri());
                Map<String, List<String>> params = queryStringDecoder.parameters();
                if (!params.isEmpty()) {
                    //URL参数传递编码-初始化编码
                    List<String> agreements = params.get("agreement");
                    xin.alum.aim.model.Aim.Agreement agreement = agreements == null ? getProperties().getAgreement() : xin.alum.aim.model.Aim.Agreement.valueOf(agreements.get(0));
                    ctx.pipeline().channel().attr(AimAttr.AGREEMENT).set(agreement);

                    params.forEach((key, val) -> {
                        ctx.channel().attr(AttributeKey.valueOf(key)).set(val.size() == 1 ? val.get(0) : val);
                    });
                }
                res = new DefaultFullHttpResponse(req.protocolVersion(), OK);
                if (Aim.request.onHandShake(ctx.channel(), req, res)) {
                    ChannelFuture f = handshake.handshake(ctx.channel(), req);
                    f.addListener(t -> {
                        if (t.isSuccess()) {
                            Aim.request.onHandShaked(ctx.channel());
                        } else {
                            logger.error("{} 握手失败", f.channel());
                        }
                    });
                } else {
                    logger.error("{} 握手被拒绝{}", ctx.channel(), res.getStatus());
                    //拒绝接入
//                WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
                    reject(ctx.channel(), res);
                }
            }
        } else if (uri.getPath().equals("/t")) {
            ByteBuf content = WebSocketServerBenchmarkPage.getContent(getWebSocketLocation(req));
            res = new DefaultFullHttpResponse(req.protocolVersion(), OK, content);
            res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
            HttpUtil.setContentLength(res, content.readableBytes());
            sendHttpResponse(ctx, req, res);
        }
    }

    /**
     * 拒绝接入 自定义返回码
     *
     * @param ch
     * @param res
     * @return
     */
    private ChannelFuture reject(Channel ch, HttpResponse res) {
        res.headers().set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, WebSocketVersion.V13.toHttpHeaderValue());
//        HttpUtil.setContentLength(res, 0L);
        return ch.writeAndFlush(res, ch.newPromise());
    }

    private void handleWebSocketFrame(ChannelHandlerContext ctx, Object frame) {
        try {
            // Check for closing frame
            if (frame instanceof CloseWebSocketFrame) {
                //响应关闭
                super.onClose(ctx.channel(), AimClose.CLIENT_CLOSE);
                CloseWebSocketFrame close = ((CloseWebSocketFrame) frame).retain();
                handshake.close(ctx.channel(), close);
            } else if (frame instanceof PingWebSocketFrame) {
                ctx.writeAndFlush(new PongWebSocketFrame());
                Aim.request.onPing(ctx.channel());
            } else if (frame instanceof TextWebSocketFrame) {
                String t = ((TextWebSocketFrame) frame).text();
                ctx.executor().execute(() -> Aim.request.onText(ctx.channel(), t));
            } else if (frame instanceof BinaryWebSocketFrame) {
                Aim.request.onByte(ctx.channel(), ((BinaryWebSocketFrame) frame).content());
            }
        } catch (Exception e) {
            logger.error("WebSocket消息处理异常：{},{}", e.getMessage(), e);
        }
    }

    private String getWebSocketLocation(FullHttpRequest req) {
        String location = req.headers().get(HttpHeaderNames.HOST) + getProperties().getPath();
        if (getProperties().isSsl()) {
            return "wss://" + location;
        } else {
            return "ws://" + location;
        }
    }
}
